import Taro from "@tarojs/taro";
import axios from "axios";

const request = axios.create({
    baseURL: '',
    enableCookie:true,
    
});


// 请求拦截
request.interceptors.request.use(config => {
  let token = '';
  Taro.getStorage({
    key: 'token',
    success: function (res) {
      token = res.data
    }
  }).catch(()=>{
    console.log('no token')
  });
  if(token){
    config.headers.Authorization = 'Bearer '+token;
  }
  config.url = config.url.indexOf('/wx-course-manage-server')==-1?'/wx-course-manage-server/api/' +config.url:config.url;
  
  return config;
}, error => Promise.reject(error));

// 响应拦截
request.interceptors.response.use(
  (response)=>{
    console.log(response)
    let resData = response.data;
    const code = resData?.meta?.code || '0';
     if (code !== 200) {
        return Promise.reject(new Error(resData?.meta?.msg || 'Error'))
     }else{
        return resData.data;
     }
  },
  error => {
    console.log(error);
     // 处理网络错误
    if (!error.response) {
       Taro.showToast({
          title: '网络连接异常',
              icon: 'error',
              duration: 2000
        })
      return Promise.reject(error)
    }

    // 处理401未授权
    if (error.response.status === 401) {
      localStorage.removeItem('token')
      Taro.navigateTo({url:'/pages/login/index'});
      return Promise.reject(error)
    }
    return Promise.reject(error);
  }
);

export default request;